﻿using System.Linq;
using System.Web.Mvc;
using Quickie.Models;
using Quickie.Models.IoC;
using Quickie.Models.Data;
using Quickie.Models.Entities;
using Quickie.Models.ViewModel;
using Quickie.Models.Interfaces;

namespace Quickie.Areas.Admin.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class CompanyAdminController : Controller
    {
        private IRepository<Company> companies;
        private IRepository<Person> people;

        public CompanyAdminController(IRepository<Company> comp, IRepository<Person> pepls)
        {
            companies = comp;
            people = pepls;
        }

        public ActionResult List()
        {
            var model = companies.GetAll().ToList();
            return View(model);
        }

        public ActionResult Edit(int id)
        {
            var company = companies.GetByID(id);
            PopulateViewData(id);
            return View(company);
        }

        public ActionResult New()
        {
            var model = new Company();
            PopulateViewData(0);
            return View(model);
        }

        public ActionResult Delete(int id)
        {
            Company companyToDelete = companies.GetByID(id);
            companies.Delete(companyToDelete);
            companies.SaveChanges();

            return Redirect(Url.Action("List", "CompanyAdmin"));
        }

        [HttpPost]
        public ActionResult Save(Company company)
        {
            if (!ModelState.IsValid)
            {
                PopulateViewData(company.ID);
                return company.ID == 0 ? View("New", company) : View("Edit", company);
            }
            companies.Save(company);
            return RedirectToAction("List");
        }

        private void PopulateViewData(int ID)
        {
            var comp = companies.GetAll()
                .Where(x=>x.ID != ID)
                .OrderBy(x => x.Name)
                .Select(x => new SelectListItem()
                {
                    Text = x.Name,
                    Value = x.ID.ToString(),
                    Selected = x.ID == ID
                })
                .ToList();
            comp.Insert(0, new SelectListItem() { Text = "Root", Value = "0" });
            ViewData["comp"] = comp;
        }
    }
}
